package com.behelpful.demo.quartz.invoker;

import cn.hutool.core.util.StrUtil;
import com.behelpful.common.core.utils.SpringBeanUtil;
import com.behelpful.demo.quartz.entity.SystemJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author Alay
 * @date 2021-10-31 18:01
 * @since
 */
@Slf4j
@Service(value = "INSTANCE")
public class InstanceInvoker implements ITaskInvoker {

    @Override
    public void doInvoke(SystemJob systemJob) {
        Object returnValue;
        try {
            Class<?> taskClazz = Class.forName(systemJob.getTaskClazzName());
            Object taskBean = SpringBeanUtil.getBean(taskClazz);

            Method taskMethod = taskClazz.getDeclaredMethod(systemJob.getMethodName());
            taskMethod.setAccessible(true);

            String methodParams = systemJob.getMethodParams();
            if (StrUtil.isNotEmpty(methodParams)) {
                returnValue = taskMethod.invoke(taskBean, methodParams);
            } else {
                returnValue = taskMethod.invoke(taskBean);
            }
            if (StrUtil.isEmpty(returnValue.toString())) {
                log.error("定时任务执实例执行器: 执行异常,执行任务：{}", systemJob.getTaskClazzName());
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}